<template>
  <div>
    <el-form ref="pram" :model="pram" :rules="rules" label-width="120px" @submit.native.prevent>
      <el-form-item label="管理员账号" prop="account">
        <el-input v-model="pram.account" placeholder="管理员账号" />
      </el-form-item>
      <el-form-item label="管理员密码" prop="pwd">
        <el-input v-model="pram.pwd" placeholder="管理员密码" clearable @input="handlerPwdInput" @clear="handlerPwdInput" />
      </el-form-item>
      <el-form-item v-if="pram.pwd" label="确认密码" prop="repwd">
        <el-input v-model="pram.repwd" placeholder="确认密码" clearable />
      </el-form-item>
      <el-form-item label="管理员姓名" prop="realName">
        <el-input v-model="pram.realName" placeholder="管理员姓名" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input type="text" v-model="pram.phone" prefix="ios-contact-outline" placeholder="请输入手机号" size="large" />
      </el-form-item>
      <el-form-item label="角色" prop="roles">
        <el-select v-model="pram.roles" placeholder="角色" clearable multiple style="width: 100%">
          <el-option v-for="item,index in roleList.list" :key="index" :label="item.roleName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="管理员身份" prop="memberType">
        <el-select v-model="pram.memberType" placeholder="管理员身份" clearable style="width: 100%">
          <el-option v-for="item,index in memberTypeList" :key="index" :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户" prop="userId"
        v-if="pram.memberType != 1 && pram.memberType != null && pram.memberType != ''">
        <UserSearchable v-model="pram.userId"></UserSearchable>
      </el-form-item>
      <el-form-item label="数据场名称" prop="name"
        v-if="pram.memberType != 1 && pram.memberType != null && pram.memberType != ''">
        <el-input v-model="pram.name" placeholder="数据场名称" />
      </el-form-item>
      <el-form-item label="负责人" prop="principal"
        v-if="pram.memberType != 1 && pram.memberType != null && pram.memberType != ''">
        <el-input v-model="pram.principal" placeholder="负责人" />
      </el-form-item>
      <el-form-item label="数据场地址" prop="address"
        v-if="pram.memberType != 1 && pram.memberType != null && pram.memberType != ''">
        <el-input v-model="pram.address" placeholder="数据场地址" />
      </el-form-item>

      <el-form-item label="数据场过期时间" prop="expireTime"
        v-if="pram.memberType != 1 && pram.memberType != null && pram.memberType != ''">
         <el-date-picker
              v-model="pram.expireTime"
              type="date"
              placeholder="选择数据场过期时间">
            </el-date-picker>
      </el-form-item>

      <el-form-item label="佣金模板" prop="brokerageTemplateId" v-if="pram.memberType != 1 && pram.memberType != null && pram.memberType != ''">
        <el-select v-model="pram.brokerageTemplateId" placeholder="佣金模板" clearable style="width: 100%">
          <el-option v-for="item,index in brokerageTemplateIdList" :key="index" :label="item.brokerageTemplateName"
            :value="item.id" />
        </el-select>
      </el-form-item>


      <el-form-item label="状态">
        <el-switch v-model="pram.status" :active-value="true" :inactive-value="false" active-text="开启"
          inactive-text="关闭" />
      </el-form-item>
      <el-form-item label="备注：" v-if="pram.memberType != 1 && pram.memberType != null && pram.memberType != ''">
        <el-input type="textarea" v-model="pram.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSubmit('pram')"
          v-hasPermi="['admin:system:admin:update','admin:system:admin:save']">{{ isCreate===0?'確定':'更新' }}</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>

    <!--用户列表-->
    <el-dialog append-to-body="true" modal-append-to-body="false" title="用户列表" :visible.sync="userVisible" width="900px"
       :close-on-click-modal="false" :close-on-press-escape="false">
      <user-list v-if="userVisible" @getTemplateRow="getTemplateRow"></user-list>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userclose()">取 消</el-button>
        <el-button type="primary" @click="usersubmit()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import * as roleApi from '@/api/role.js'
  import * as agentApi from '@/api/agent.js'
  import * as systemAdminApi from '@/api/systemadmin.js'
  import {
    Debounce
  } from '@/utils/validate'
  import userList from '@/components/userList'
  import UserSearchable from "@/components/UserSearchable";
  export default {
    components: {
      userList,
      UserSearchable
    },
    props: {
      isCreate: {
        type: Number,
        required: true
      },
      editData: {
        type: Object,
        default: () => {
          return {
            rules: []
          }
        }
      }
    },
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请填写手机号'));
        } else if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error('手机号格式不正确!'));
        } else {
          callback();
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.pram.pwd) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        constants: this.$constants,
        pram: {
          account: null,
          level: null,
          pwd: null,
          repwd: null,
          realName: null,
          roles: [],
          status: null,
          id: null,
          phone: null,
          memberType: null,
          userId: null,
          name: null,
          principal: null,
          address: null,
          expireTime: null,
          brokerageTemplateId:null,
          remark: null,
        },
        memberTypeList: [],
        brokerageTemplateIdList:[],
        roleList: [],
        rules: {
          account: [{
            required: true,
            message: '请填管理员账号',
            trigger: ['blur', 'change']
          }],
          pwd: [{
            required: true,
            message: '请填管理员密码',
            trigger: ['blur', 'change']
          }],
          repwd: [{
            required: true,
            message: '确认密码密码',
            validator: validatePass,
            trigger: ['blur', 'change']
          }],
          realName: [{
            required: true,
            message: '管理员姓名',
            trigger: ['blur', 'change']
          }],
          roles: [{
            required: true,
            message: '角色',
            trigger: ['blur', 'change']
          }],
          phone: [{
            required: true,
            message: '请输入手机号',
            trigger: ['blur', 'change']
          }]
        },
        userVisible: false,
      }
    },
    mounted() {
      this.getMemberTypeList()
      this.initEditData()
      this.handleGetRoleList()
      this.getbrokerageTemplateIdList()
    },
    methods: {
      selectUser() {
        this.userVisible = true
      },
      getTemplateRow(row) {
        this.pram.userId = row.uid
      },
      userclose() {
        this.pram.userId = ''
        this.userVisible = false
      },
      usersubmit() {
        this.userVisible = false
      },
      getMemberTypeList() {
        roleApi.sysDictDataType('yj_admin_member_type').then(res => {
          this.memberTypeList = res
        })
      },
      getbrokerageTemplateIdList(){
        agentApi.brokeragetemplateGetOption().then(res => {
          this.brokerageTemplateIdList = res
        })
      },
      close() {
        this.$emit('hideEditDialog')
      },
      handleGetRoleList() {
        const _pram = {
          page: 1,
          limit: this.constants.page.limit[4],
          status: 1
        }
        roleApi.getRoleList(_pram).then(data => {
          this.roleList = data;
          let arr = [];
          data.list.forEach(item => {
            arr.push(item.id);
          })
          if (!arr.includes(Number.parseInt(this.pram.roles))) {
            this.$set(this.pram, 'roles', []);
          }
        })
      },
      initEditData() {
        if (this.isCreate !== 1) return
        const {
          account,
          realName,
          roles,
          level,
          status,
          id,
          phone,
          memberType,
          userId,
          name,
          principal,
          address,
          expireTime,
          brokerageTemplateId,
          remark
        } = this.editData
        this.pram.account = account
        this.pram.realName = realName
        const _roles = []
        if (roles.length > 0 && !roles.includes(',')) {
          //如果权限id集合有长度并且是只有一个，就将它Push进_roles这个数组
          _roles.push(Number.parseInt(roles))
        } else {
          //否则就将多个id集合解构以后push进roles并且转换为整型
          _roles.push(...roles.split(',').map(item => Number.parseInt(item)))
        }
        this.pram.roles = _roles
        this.pram.status = status
        this.pram.id = id
        this.pram.phone = phone
        this.rules.pwd = []
        this.rules.repwd = []
        this.pram.memberType = String(memberType)
        this.pram.userId = userId
        this.pram.name = name
        this.pram.principal = principal
        this.pram.address = address
        this.pram.expireTime = expireTime
        this.pram.brokerageTemplateId = brokerageTemplateId
        this.pram.remark = remark
      },
      handlerSubmit: Debounce(function(form) {
        this.$refs[form].validate(valid => {
          if (!valid) return
          if (this.isCreate === 0) {
            this.handlerSave()
          } else {
            this.handlerEdit()
          }
        })
      }),
      handlerSave() {
        systemAdminApi.adminAdd(this.pram).then(data => {
          this.$message.success('创建管理员成功')
          this.$emit('hideEditDialog')
        })
      },
      handlerEdit() {
        this.pram.roles = this.pram.roles.join(',')
        systemAdminApi.adminUpdate(this.pram).then(data => {
          this.$message.success('更新管理员成功')
          this.$emit('hideEditDialog')
        })
      },
      rulesSelect(selectKeys) {
        this.pram.rules = selectKeys
      },
      handlerPwdInput(val) {
        if (!val) {
          this.rules.pwd = []
          this.rules.repwd = []
          return
        }
        this.rules.pwd = [{
            required: true,
            message: '请填管理员密码',
            trigger: ['blur', 'change']
          },
          {
            min: 6,
            max: 20,
            message: '长度6-20个字符',
            trigger: ['blur', 'change']
          }
        ]
        this.rules.repwd = [{
          required: true,
          message: '两次输入密码不一致',
          validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('两次输入密码不一致!'))
            } else if (value !== this.pram.pwd) {
              callback(new Error('两次输入密码不一致!'))
            } else {
              callback()
            }
          },
          trigger: ['blur', 'change']
        }]
      }
    }
  }
</script>

<style scoped>

</style>
